﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.NetworkInformation;
using System.Net.Sockets;
using System.Text;
using System.Threading.Tasks;

namespace ParallelLib.Micro
{
    internal class Utils
    {
        public static bool IsLocalIpAddress(string address)
        {
            var localIPs = System.Net.Dns.GetHostAddresses(System.Net.Dns.GetHostName());
            return localIPs.Any(e => e.Equals(System.Net.IPAddress.Parse(address)));
        }

        private static IEnumerable<UnicastIPAddressInformation> cachedIPInfo = null;

        public static IEnumerable<UnicastIPAddressInformation> GetAddress()
        {
            if (cachedIPInfo != null)
                return cachedIPInfo;
            var interfaces = NetworkInterface.GetAllNetworkInterfaces()
                .Where(i => i.OperationalStatus == OperationalStatus.Up &&
                            i.NetworkInterfaceType != NetworkInterfaceType.Loopback &&
                            i.NetworkInterfaceType != NetworkInterfaceType.Ppp);

            var addresses = interfaces
                .SelectMany(i => i.GetIPProperties().UnicastAddresses
                                  .Where(a => a.Address.AddressFamily == AddressFamily.InterNetwork));
            cachedIPInfo = addresses;
            return cachedIPInfo;
        }
    }
}
